#include "JarvCore.h"
#include "ScopedLock.h"
#include "Pinger.h"
#include "HTTPServer.h"
SK

JarvCore::JarvCore()
{
	processCommandLine ();
	//speechLock = new Lock ();
    pool = new ThreadPool (64);
    //pool->start();
}

JarvCore::~JarvCore()
{
	#ifdef JARVSPEECH
    delete speech;
	::CoUninitialize();

	delete speechLock;
    #endif
    delete pool;
}

void JarvCore::processCommandLine ()
{
	String cmdline = GetCommandLine ();
	
	if (cmdline.length() == 0)
	{
		appPath = String (_T(""));
	}
	else
	{
		if (cmdline[0] == _T('\"'))
		{
			//Find the second quote
			size_t end = cmdline.find (_T("\""),1);

			if (end != std::string::npos)
				appPath = cmdline.substr (1, end-1);
			else
				appPath = cmdline.substr (1, cmdline.length() -1);
		}
		else
		{
			//path not in "" so it ends with space
			size_t end = cmdline.find (_T(" "), 1);

			if (end != std::string::npos)
				appPath = cmdline.substr (0,end-1);
			else
				appPath = cmdline;
		}

		//Remove the filename from the end of the path
		size_t pathEnd = appPath.find_last_of (_T("\\"));

		if (pathEnd != std::string::npos)
			appPath = appPath.substr (0,pathEnd+1);
	}
}

void JarvCore::init (void)
{
    //Pinger *p = new Pinger ();
    //p->ping ("172.17.11.45", "127.0.0.1");
    WSAData dat;
    WSAStartup (MAKEWORD(2,2), &dat);

    Socket *s = new Socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(s->connect ("www.google.co.uk", 80))
    {
        String req = "GET / HTTP/1.1\r\nhost: www.google.co.uk\r\n\r\n";
        s->send (req);

        byte buffer [4096];
        int ret = s->recv (buffer, 4096);
        buffer [ret] = 0;
        String res = (char *)buffer;
        std::cout << res;
        s->close();

    }



    //delete p;
    HTTPServer *sr = new HTTPServer ("C:\\",81);
    sr->start();

	//start web server
	//SocketListenerTask *tsk = new SocketListenerTask (this,82);
	//pool->queueTask (tsk);
}


void JarvCore::speak (const String& text)
{

}

void JarvCore::scheduleTask (Task *task)
{
	pool->queueTask (task);

}

EK